package org.yanex.project.api.parsers;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class XMLParser extends AbstractParser {

	@Override
	public List<ParsedItem> getItems(String text)
			throws ParserException {
		List<ParsedItem> items = new ArrayList<ParsedItem>();

		try {
			DocumentBuilderFactory builderFactory = 
					DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = builderFactory.newDocumentBuilder();
			
			Document document = builder.parse(
					new InputSource(new StringReader(text)));
			Element rootElement = document.getDocumentElement();

			NodeList listItems = rootElement.getChildNodes();

			for (int i = 0; i < listItems.getLength(); ++i) {
				if (listItems.item(i) instanceof Element) {
					Element item = (Element) listItems.item(i);
					
					if (item.getNodeName().equals("item")) {
						ParsedItem pi = new ParsedItem();
						NodeList attributes = item.getChildNodes();

						for (int j = 0; j < attributes.getLength(); ++j) {
							if (attributes.item(j) instanceof Element) {
								Element attribute = (Element) attributes
										.item(j);

								Field f = FieldConverter.getField(attribute
										.getNodeName());
								if (f != null) {
									pi.put(f, attribute.getTextContent());
								}
							}
						}
						
						items.add(pi);
					}
				}
			}
		} catch (SAXException e2) {
			throw new ParserException("Error while parsing XML document.");
		} catch (IOException e3) {
			throw new ParserException("Error while fetching XML document.");
		} catch (ParserConfigurationException e4) {
			throw new ParserException("XML parser configuration error.");
		}

		return items;
	}

}
